<template>
  <div class="lottery">
    <div class="title">{{ config.name }}</div>
    <div class="h2">
      <div>未被抽中的项</div>
      <div>抽签结果</div>

    </div>
    <div class="col3">
      <div class="items">
        <div v-for="item in unchecks" :key="item.index" :class="{ 'selected': config.s1 == item.index }"
          @click="config.s1 = item.index;">{{ item.name }}</div>
      </div>
      <div>
        <button class="btn" v-if="!config.play" @click="doStart();">
          <div class="plain-btn">开始抽签</div>
        </button>
        <button class="btn" v-else @click="doEnd();">
          <div class="plain-btn red">停止抽签</div>
        </button>
        <div class="btn">
          <div class="plain-btn red" v-if="!config.play" style="height:  224px;">等待中</div>
          <div class="plain-btn" v-else>
            <div class="items"
              style="height:  220px;width: 100%; border: none; background-color: #0000; align-items: center; flex-direction: column; justify-content: center; display: flex; ">
              <div v-for="item in randoms" :key="item.index" style=" text-align: center; color: #F00;; ">{{ item.name }}
              </div>
            </div>
          </div>
        </div>

        <div class="info">每次抽取个数<span>{{ config.num }}</span></div>
        <button class="btn" @click="openSetWindow">设<span style="padding: 0 1em;"></span>置</button>
        <button class="btn" @click="readData">打开文件</button>
        <button class="btn" @click="writeData">保存结果</button>
        <button class="btn" @click="reset">重新开始</button>
      </div>
      <div class="items num">
        <div v-for="item in checks" :class="{ 'selected': config.s2 == item.index }" :key="item.index"
          @click="config.s2 = item.index;">{{ item.name }}</div>
      </div>
    </div>

  </div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { selectAndReadFile, randomSample, selectAndWriteFile, readConfig } from '@/util'
import { message } from '@tauri-apps/plugin-dialog';
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
import { Window } from '@tauri-apps/api/window'




const openSetWindow = async () => {
  // 获取当前主窗口的实例
  const mainWindow = Window.getCurrent();



  // 定义模态窗口的选项
  const modalOptions = {
    width: 694,
    height: 287,
    decorations: true,
    alwaysOnTop: true,
    transparent: false,
    resizable: false,
    title: "设置",
    center: true,
    parent: mainWindow,
    theme: "Light",
    url: 'index.html#/set'
  };
  const webview = new WebviewWindow('set-win', modalOptions);
  webview.once('tauri://created', function () {
    webview.once('ok-config', function () {
      webview.emit('set-config', config.value);
    });
    webview.once('get-config', function (e) {
      config.value = { ...config.value, ...e.payload };
    });
  });
  webview.once('tauri://error', function (e) {
    // an error happened creating the webview
    console.log('an error happened creating the webview', e)
  });
}



const play = ref(false);

const defaultConfig = {
  name: '抽签程序',
  play: false,
  s1: -1,
  s2: -1,
  num: 5,
  index: 0,
}

const config = ref({ ...defaultConfig });

const configs = ref([]);

const list = ref([]);
const randoms = ref([]);
const selecteds = ref([-1, -1]);

const reset = () => {
  config.value = {
    ...config.value, ...{
      play: false,
      s1: -1,
      s2: -1,
      index: 0,
    }
  };
  list.value = [];
}


const unchecks = computed(() => {
  return list.value.filter(item => item.checked == -1);
});
const checks = computed(() => {
  return list.value.filter(item => item.checked > -1).sort((a, b) => a.checked - b.checked);
});

const readData = async () => {
  try {
    const data = await selectAndReadFile();
    if (data) {
      reset();
      list.value = data.trim().split('\n').map((item, index) => ({ index, name: item.trim(), checked: -1 }));
    }
  } catch (err) {
    await message(err.toString(), { title: '系统消息', kind: 'error' });;
  }
}

const writeData = async () => {
  if (checks.value.length == 0) {
    message('请先抽签', { title: '系统消息', kind: 'error' });
    return;
  }
  try {
    const data = checks.value.map(item => item.name).join('\n');
    await selectAndWriteFile(data, config.value.name + '.txt');
  } catch (err) {
    // await message(err.toString(), { title: '系统消息', kind: 'error' });
  }
}

const doEnd = () => {
  config.value.play = false;
  randomSample(unchecks.value, config.value.num).forEach(item => item.checked = config.value.index++);
}




const doStart = () => {
  if (unchecks.value.length < config.value.num) {
    message('未被抽中的项不足', { title: '系统消息', kind: 'error' });
    return;
  }

  config.value.play = true;

  playRandom();
}


const playRandom = () => {
  if (!config.value.play) {
    return;
  }
  randoms.value = randomSample(unchecks.value, config.value.num);
  requestAnimationFrame(playRandom);
}

onMounted(async () => {
  configs.value = await readConfig();
})

</script>
<style scoped lang="scss">
.info {
  font-family: '新宋体', sans-serif;
  box-sizing: border-box;
  display: flex;
  width: 100%;
  min-height: 36px;
  font-size: 30px;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  transform: translateY(-2px);

  &>span {
    color: #3399fc;
    margin-left: 1em;
  }
}

.btn {
  font-family: '新宋体', sans-serif;
  border: solid 1px #adadad;
  box-sizing: border-box;
  display: flex;
  font-weight: bold;
  width: 100%;
  min-height: 38px;
  font-size: 30px;
  justify-content: center;
  align-items: center;
  padding: 1px;
  background-color: #e1e1e1;
  margin-bottom: 6px;

  &:hover {
    background-color: #e5f1fb;
    border-color: #0078d7;
  }

  &:active {
    background-color: #cce4f7;
    border-color: #005499;
  }

}

.plain-btn {
  width: 100%;
  background-color: #b9d1ea;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 94px;
}

.plain-btn.red {
  color: #f00;
}

.lottery {
  box-sizing: border-box;
  background-color: #f0f0f0;
  width: 1126px;
  height: 673px;
  padding: 16px;
  display: block;
  position: relative;
  font-weight: normal;
  /* background-image: url('./1.png');
  background-repeat: no-repeat; */



  .items {
    border: solid 1px #828790;
    height: 530px;
    overflow: auto;
    padding: 2px 3px;
    background-color: #ffffe1;

    &.num {
      counter-reset: counter;

      &>div {
        counter-increment: counter;

        &::before {
          content: '(' counter(counter) ')';
          margin-right: 5px;
        }
      }
    }

    &>div {
      font-size: 33px;
      color: #0869cc;
      font-weight: bold;
      cursor: default;
      text-align: left;

      &.selected {
        background-color: #0869cc;
        color: #fff;
      }
    }
  }

  .col3 {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 16px;
    padding: 8px 0 0 0;
    min-height: 530px;
  }

  .h2 {
    font-size: 32px;
    color: #000;
    font-weight: bold;
    text-align: center;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 17px 93px 0 40px;


  }

  .title {
    padding-top: 3px;
    grid-column: span 3;
    height: 48px;
    font-size: 48px;
    line-height: 1;
    color: #0066cc;
    font-weight: bold;
    text-align: center;
  }
}
</style>
